<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\common\manager;

use app\common\model\Team;
use app\common\model\User;
use app\common\model\UserTeam;
use app\common\model\WriteOff;
use think\Db;
use think\Exception;

class WriteOffManager extends BaseManager
{

    public static function writeOff(User $user,string $verify_code,bool $trans=true):array
    {
        if ($trans)
            Db::startTrans();
        try {
            $userTeamModel = new UserTeam();
            if ($user->is_captain != User::IS_CAPTION_YES){
                throw new Exception('您不是队长，无法操作');
            }
            if (!$verifyInfo = $userTeamModel::where('verif_code', $verify_code)->find()){
                throw new Exception('当前核销码记录不存在');
            }

            if ($user->id != Team::where('t_id',$verifyInfo['team'])->value('captain')){
                throw new Exception('您无法操作此记录');
            }

            if ($verifyInfo['state'] == UserTeam::STATE_WRITE_OFF){
                throw new Exception('当前记录已核销，无法再次核销');
            }

            if ($verifyInfo['pay_state'] != UserTeam::PAY_STATUS_SUCCESS){
                throw new Exception('当前记录无法核销');
            }

            if(!$offInfo = WriteOff::create([
                'type'=> WriteOff::TYPE_TEAM,
                'writer'=>$user->id,
                'user_id'=>$verifyInfo['user_id'],
                'relation_id'=>$verifyInfo['ut_id'],
                'create_time'=>time(),
            ])){
                throw new Exception('当前记录核销失败');
            }

            if(!UserTeam::where('ut_id',$verifyInfo['ut_id'])->update(['state'=>UserTeam::STATE_WRITE_OFF,'write_off_id'=>$offInfo->id,'up_date'=>time()])){
                throw new Exception('核销记录修改失败');
            }
            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }

        return ['code'=>self::getStatusCode(),'message'=>self::getMessage()];
    }
}